package com.zw.yzk.kabu.base;

import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.exception.CustomException;
import com.zw.yzk.kabu.domain.interactor.DefaultSubscriber;
import com.zw.yzk.kabu.management.ExceptionHandle;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.view.widget.LoginStateInvalidDialog;

/**
 * Created by zhanwei on 2016/12/23.
 */

public abstract class BaseSubscriber<T> extends DefaultSubscriber<T> {
    private AppCompatActivity activity;

    public BaseSubscriber(AppCompatActivity appCompatActivity) {
        this.activity = appCompatActivity;
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        onCompleted();
        dealErrorMessage(e);
    }

    @Override
    public void onNext(T t) {
        super.onNext(t);
    }

    /**
     * 错误处理
     *
     * @param e 异常
     */
    private void dealErrorMessage(Throwable e) {
        e.printStackTrace();
        CustomException exception = ExceptionHandle.handleException(e, activity);
        if (TextUtils.isEmpty(exception.getErrMsg())) {
            switch (exception.getErrCode()) {
                case Constant.UNKNOWN_ERROR:
                    showErrorMessage(activity.getResources().getString(R.string.unknown_error), exception.getErrCode());
                    break;
                case Constant.UNKNOWN_INVALID_TOKEN:
                    new LoginStateInvalidDialog().showInvalidDialog(activity, activity.getResources().getString(R.string.invalid_token));
                    break;
                case Constant.MUST_LOGIN:
                    new LoginStateInvalidDialog().showInvalidDialog(activity, activity.getResources().getString(R.string.must_login));
                    break;
                default:
                    showErrorMessage(addErrorMessage(), exception.getErrCode());
                    break;
            }
        } else {
            showErrorMessage(exception.getErrMsg(), exception.getErrCode());
        }
    }

    /**
     * 展示错误信息
     *
     * @param msg 错误信息
     */
    private void showErrorMessage(String msg, int errorCode) {
        String errorInfo = msg + "(" + errorCode + ")";
        ToastManager.getInstance().showToast(activity, errorInfo);
    }

    /**
     * 当服务器返回错误且没有给出错误说明时调用
     *
     * @return 错误信息
     */
    public abstract String addErrorMessage();

}
